﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;

namespace MICZ.CodeBuilder.Commons.JsonExtensions
{
    /// <summary>
    /// Json帮助类
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 获取Json实体by字符串
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
        /// <returns>对象实体</returns>
        public static T GetJsonModelByString<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            object o = new object();
            try
            {
                #region 如果有数组对象
                Regex regex = new Regex(@"\[(.|\w|\W|\s|\S)+?\]");
                MatchCollection matches= regex.Matches(json);
                if (matches.Count > 0)
                {
                    foreach (var item in matches)
                    {
                        json = json.Replace(item.ToString(),item.ToString().Replace("\",\"",","));
                    }
                    json = json.Replace("[","").Replace("]","");
                }
                #endregion
                StringReader sr = new StringReader(json);
                o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
                T t = o as T;
                return t;
            }
            catch (Exception ex)
            {
                //TTvCore.Common.Helper.LogHelper.LogError("Json转换出错！", ex, json);
            }
            T t1 = new object() as T;
            return t1;
        }
        /// <summary>
        /// 解析JSON数组生成对象实体集合
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
        /// <returns>对象实体集合</returns>
        public static List<T> GetJsonListModelByString<T>(string json) where T : class
        {
            #region 如果有数组对象
            Regex regex = new Regex(@"\[(.|\w|\W|\s|\S)+?\]");
            MatchCollection matches = regex.Matches(json);
            if (matches.Count > 0)
            {
                foreach (var item in matches)
                {
                    json = json.Replace(item.ToString(), item.ToString().Replace("\",\"", ","));
                }
                json = json.Replace("[", "").Replace("]", "");
            }
            #endregion
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        }

        /// <summary>
        /// 获取Json字符串By实体Model
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string GetJsonStringByModel(object o)
        {
            string json = JsonConvert.SerializeObject(o);
            return json;
        }
        /// <summary>
        /// 反序列化JSON到给定的匿名对象.
        /// </summary>
        /// <typeparam name="T">匿名对象类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <param name="anonymousTypeObject">匿名对象</param>
        /// <returns>匿名对象</returns>
        public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
        {
            T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
            return t;
        }


        /// <summary>
        /// 反序列化XML到JSON字符串.
        /// </summary>
        /// <param name="xml">json字符串</param>
        /// <returns>json</returns>
        public static string GetXmlByJson(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return "";
            }
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            string json = JsonConvert.SerializeXmlNode(doc);
            return json;
        }

        /// <summary>
        /// 获取配置文件内容
        /// </summary>
        /// <param name="pathUrl">参数（Config/WeChar/NoPublicAppConfig.json）</param>
        /// <param name="param">参数（AppSetting:NoHttpsHost）</param>
        /// <returns></returns>
        public static string GetJsonConfig(string pathUrl, string param)
        {
            IConfiguration Configuration = new ConfigurationBuilder()
                   .SetBasePath(Directory.GetCurrentDirectory())
                   .Add(new JsonConfigurationSource { Path = pathUrl, ReloadOnChange = true })
                   .Build();
            return Configuration.GetSection(param).Value + "";
        }

    }
}
